import React from 'react';
import { Icon, Tooltip } from 'antd';
import { connect } from 'dva';
import { Form, FormItem, createFormActions, FormEffectHooks } from '@formily/antd';
import { Input, Switch, Range, DatePicker } from '@formily/antd-components';
import classNames from 'classnames';
import throttle from 'lodash/throttle';
import omit from 'lodash/omit';
import find from 'lodash/find';
import { hasKey, getStepMarks } from '../utils';
import styles from '../../styles.less';

const actions = createFormActions();
const { onFieldValueChange$, onFormInputChange$ } = FormEffectHooks;

// TODO: 年选择暂不支持
function ForYearPicker({ dispatch, current, columnNum }) {
  let initialValues = { ...current };

  /**
   * 1、序列化
   */
  if (hasKey(initialValues, 'rules') && Array.isArray(initialValues.rules)) {
    const requiredRule = find(initialValues.rules, 'required');
    const formatRule = find(initialValues.rules, 'format');
    const patternRule = find(initialValues.rules, 'pattern');

    initialValues = {
      ...initialValues,
      isFormat: formatRule !== undefined,
      isPattern: patternRule !== undefined,
    };

    if (requiredRule) {
      initialValues = {
        ...initialValues,
        requiredRule,
      };
    }

    if (formatRule) {
      initialValues = {
        ...initialValues,
        formatRule,
      };
    }

    if (patternRule) {
      initialValues = {
        ...initialValues,
        patternRule,
      };
    }
  }

  return (
    <Form
      initialValues={initialValues}
      className={classNames(styles.configForm)}
      actions={actions}
      colon={false}
      effects={({ setFieldState }) => {
        // 只监控人工操作引起的FormItem值变化
        onFormInputChange$().subscribe(
          throttle(
            () => {
              let formValues = actions.getFormState().values;
              const newRules = [];

              /**
               * 1、序列化
               * 2、添加和移除规则（添加时防止重复），并且只有输入关键字段时才更新，比如 format值不存在时不会提交对应的message
               * 3、剔除冗余字段
               */
              if (hasKey(formValues, 'requiredRule')) {
                newRules.push({ ...formValues.requiredRule, whitespace: true, message: '必填项' });
              }

              if (hasKey(formValues, 'formatRule') && formValues.formatRule.format) {
                newRules.push(formValues.formatRule);
              }

              if (hasKey(formValues, 'patternRule') && formValues.patternRule.pattern) {
                newRules.push(formValues.patternRule);
              }

              formValues = omit({ ...formValues, rules: newRules }, [
                'isFormat',
                'isPattern',
                'requiredRule',
                'formatRule',
                'patternRule',
                'level',
              ]);

              dispatch({
                type: 'formDesigner/updateNode',
                payload: formValues,
              });
            },
            300,
            { trailing: true, leading: false }
          )
        );

        // 监听：checked时，展示对应的输入框
        onFieldValueChange$('isFormat').subscribe(({ value: checked }) => {
          setFieldState('formatRule.format', state => {
            state.visible = checked;
          });

          setFieldState('formatRule.message', state => {
            state.visible = checked;
          });
        });

        onFieldValueChange$('isPattern').subscribe(({ value: checked }) => {
          setFieldState('patternRule.pattern', state => {
            state.visible = checked;
          });

          setFieldState('patternRule.message', state => {
            state.visible = checked;
          });
        });
      }}
    >
      <FormItem
        label="标题"
        name="label"
        allowClear
        required
        triggerType="onChange"
        component={Input}
        placeholder="无"
      />

      <FormItem
        label="字段名称"
        name="name"
        allowClear
        required
        disabled
        triggerType="onChange"
        component={Input}
      />

      <FormItem
        label={
          <>
            水平跨度
            <Tooltip title="1表示占满一行">
              <Icon type="info-circle" className={styles.helpIcon} />
            </Tooltip>
          </>
        }
        style={{ width: '150px' }}
        name="span"
        triggerType="onChange"
        min={1}
        step={1}
        max={columnNum}
        marks={getStepMarks(columnNum)}
        component={Range}
      />

      <FormItem
        label={
          <>
            标题长度
            <Tooltip title="标题 + 输入框 <=24">
              <Icon type="info-circle" className={styles.helpIcon} />
            </Tooltip>
          </>
        }
        style={{ width: '150px' }}
        name="labelCol"
        triggerType="onChange"
        min={1}
        step={1}
        max={24}
        initialValue={8}
        marks={{ 1: '1', 24: '24' }}
        component={Range}
      />

      <FormItem
        label={
          <>
            输入框长度
            <Tooltip title="标题 + 输入框 <=24">
              <Icon type="info-circle" className={styles.helpIcon} />
            </Tooltip>
          </>
        }
        style={{ width: '150px' }}
        name="wrapperCol"
        triggerType="onChange"
        min={1}
        step={1}
        max={24}
        initialValue={16}
        marks={{ 1: '1', 24: '24' }}
        component={Range}
      />

      {/* <FormItem
        label="占位内容"
        allowClear
        name="placeholder"
        triggerType="onChange"
        component={Input}
        placeholder="无"
      /> */}

      <FormItem
        label="初始值"
        name="initialValue"
        triggerType="onChange"
        component={DatePicker.YearPicker}
        placeholder="无"
      />

      <FormItem
        label="只读"
        name="disabled"
        // labelCol={6}
        // wrapperCol={16}
        triggerType="onChange"
        component={Switch}
        // size="small"
        initialValue={false}
      />

      <FormItem
        label="显示"
        name="display"
        // labelCol={6}
        // wrapperCol={16}
        triggerType="onChange"
        component={Switch}
        // size="small"
        initialValue
      />

      <FormItem
        label="必填"
        // labelCol={6}
        // wrapperCol={16}
        name="requiredRule.required"
        triggerType="onChange"
        component={Switch}
        // size="small"
        initialValue={false}
      />

      {/* <FormItem
        label="类型"
        // labelCol={6}
        // wrapperCol={16}
        name="isFormat"
        triggerType="onChange"
        component={Switch}
        // size="small"
        initialValue={false}
      />

      <FormItem
        name="formatRule.format"
        triggerType="onChange"
        component={Select}
        dataSource={[
          {
            label: '中文',
            value: 'zh',
          },
          {
            label: '手机号',
            value: 'phone',
          },
          {
            label: '邮箱',
            value: 'email',
          },
          {
            label: 'URL',
            value: 'url',
          },
          {
            label: '日期',
            value: 'date',
          },
        ]}
        allowClear
        placeholder="选择数值类型"
      />
      <FormItem
        allowClear
        name="formatRule.message"
        triggerType="onChange"
        component={Input}
        placeholder="自定义错误提示"
      />

      <FormItem
        label="正则"
        // labelCol={6}
        // wrapperCol={16}
        name="isPattern"
        triggerType="onChange"
        component={Switch}
        // size="small"
        initialValue={false}
      />
      <FormItem
        name="patternRule.pattern"
        triggerType="onChange"
        allowClear
        component={Input}
        rules={[
          {
            validator(value) {
              if (isStrRegExp(value)) {
                return '';
              }
              return '不是有效的正则表达式';
            },
          },
        ]}
        placeholder="正则表达式"
      />
      <FormItem
        allowClear
        name="patternRule.message"
        triggerType="change"
        component={Input}
        placeholder="自定义错误提示"
      /> */}
    </Form>
  );
}

export default connect(({ formDesigner }) => ({
  current: formDesigner.current,
  columnNum: formDesigner.columnNum,
}))(ForYearPicker);
